import {
  getBannersData,
  getPlaylistData
} from '../../services/music-api'
import {getElementRect} from '../../utils/getElementRect'
import {debounce} from '../../utils/debounce'
import {rankStore,musicStore} from '../../store/index'
const _debounceOfGetElementRect = debounce(getElementRect)
Page({
  data: {
    banners:[],
    swiperHeight:0,
    hotSongList:[], //1
    hotPlaylists:[],
    recommendPlaylists:[],
    ranks:{0:{},2:{},3:{}},
    currentSong:{},
    isShowPlaybar:false,
    isPlaying:true,
    playAnimState:"paused"
  },
  onLoad: function (options) {
    getBannersData().then(res => {
      const banners = res.banners
      this.setData({banners})
    })
    getPlaylistData(6).then(res => {
      const hotPlaylists = res.playlists
      this.setData({hotPlaylists})
    })
    getPlaylistData(6,'华语').then(res => {
      const recommendPlaylists = res.playlists
      this.setData({recommendPlaylists})
    })
    rankStore.dispatch('getRankSongInfo')
    rankStore.onState('hotRankInfo',(value) => {
      if(Object.keys(value).length === 0 ) return 
      const hotSongList = value.tracks?.slice(0,6)
      this.setData({hotSongList})
    })
    rankStore.onState('newRankInfo',this.handleRankInfo(0))
    rankStore.onState('createRankInfo',this.handleRankInfo(2))
    rankStore.onState('fastRankInfo',this.handleRankInfo(3))
    musicStore.onState('songInfo',value => { 
      this.setData({
        isShowPlaybar:Object.keys(value).length !== 0,
        currentSong:value
      })
    })
    musicStore.onState('isPlaying',value => {
      this.setData({
        isPlaying:value,
        playAnimState:value? 'running':"paused"
      })
    })
  },
  handleRankInfo(idx){
    return (value) => {
      if(Object.keys(value).length === 0) return 
      value.idx = idx
      const ranks = {...this.data.ranks,[idx]:value}
      this.setData({ranks})
    }
  },
  handleImgLoad(){
    _debounceOfGetElementRect('.item-img').then(res => {
      const swiperHeight = res[0].height
      this.setData({swiperHeight})
    })
  },
  changeMusicState(){
    musicStore.dispatch('changeMusicStatusAction',!this.data.isPlaying)
  },
  goToMusicDetail(){
    wx.navigateTo({
      url:`/pages/music-detail/index?id=${this.data.currentSong.id}`,
    })
  },
  handleSearchFocus(){
    wx.navigateTo({
      url: '/pages/search-detail/index',
    })
  }
})